from django.shortcuts import render
from modular.mysqldb.Password import AES_ENCRYPT
from modular.mysqldb.logindb import Users
from django.shortcuts import HttpResponse
from django.http.response import JsonResponse
import json


def register(request):
    global json
    if request.method == 'GET':
        return render(request, 'register.html')
    else:
        aes_encrypt = AES_ENCRYPT()
        user = request.POST.get('account')
        pwd = aes_encrypt.jiami(request.POST.get('password'))
        name = request.POST.get('name')
        sex = request.POST.get('sex')
        # 注册
        zc = Users.objects.create(account=user, password=pwd, name=name, sex_id=sex)
        zc.save()
        num = Users.objects.filter(account=user).count()
        if num == 1:
            data = [{
                'code': "200",
                'context': '注册成功',
                'other': name
            }]
            return JsonResponse(data)
        else:
            data = [{
                'code': "500",
                'context': '注册失败',
                'other': 'error'
            }]
            return JsonResponse(data)


def isItRegistered(request):
    global json
    if request.method == 'POST':
        user = json.loads(request.body.decode('utf-8'))
        account = user['account']
        num = Users.objects.filter(account=account).count()
        if num == 1:
            data = {
                'code': '200',
                'context': '注册失败',
                'other': '账户已存在'
            }
            return JsonResponse(data)
        else:
            data = {
                'code': '500',
                'context': '账户可注册',
                'other': ''
            }
            return JsonResponse(data)
    else:
        pass
